package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @Author: qingtao
 * @Date 2022/3/8 10:06
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    /**
     * 获取一个session
     */
    @Autowired(required = false)
    public HttpSession session;

    @Autowired(required = false)
    private EmployeeService employeeService;

    /**
     * 登录
     *
     * @param employee
     * @return
     */
    @RequestMapping("/login")
    public R<Employee> login(@RequestBody Employee employee) {
        R<Employee> r = employeeService.login(employee);
        if (r.getCode() == 1) {
            session.setAttribute("employee", r.getData().getId());
        }

        return r;
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout() {
        session.invalidate(); //清除会话
        return R.success("退出成功");
    }

    /**
     * 分页查找
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @RequestMapping("/page")
    public R<Page<Employee>> findByPage(Integer page, Integer pageSize, String name) {
        Page<Employee> employeePage = employeeService.findByPage(page, pageSize, name);
        return R.success(employeePage);
    }

    /**
     * 添加
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        Long employee1 = (Long) session.getAttribute("employee");
        employee.setCreateUser(employee1);
        employee.setUpdateUser(employee1);
        boolean save = employeeService.save(employee);
        if (save) {
            return R.success("添加成功");
        } else {
            return R.error("添加失败");
        }
    }

    /**
     * 回显
     *
     * @param id
     * @return
     */
    @RequestMapping("/{id}")
    public R<Employee> queryEmployeeById(@PathVariable Integer id) {
        Employee employee = employeeService.queryEmployeeById(id);
        return R.success(employee);
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        Long employee1 = (Long) session.getAttribute("employee");
        employee.setUpdateUser(employee1);
        if (employeeService.update(employee)) {
            return R.success("修改成功");
        } else {
            return R.error("修改失败");
        }

    }
}
